//
//  ownInforView.m
//  SoundPill
//
//  Created by 宋旭东 on 15/6/22.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "ownInforView.h"
#import "My_ViewController.h"
#import "AppDelegate.h"
#import "userInformationViewController.h"
#import "JCAlertView.h"
@interface ownInforView ()
{
    My_ViewController *my_vc;
    userInformationViewController *other_vc;
}

@end

@implementation ownInforView
- (instancetype)initWithFrame:(CGRect)frame ownuid:(NSString *)uid viewController:(UIViewController *)viewcontroller
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubviews];
        [self requestOwnInfor:uid];
        ownuid = uid;
        if ([viewcontroller isMemberOfClass:[userInformationViewController class]]) {
            other_vc = (userInformationViewController *)viewcontroller;
            my_vc = nil;
            _headerButton.frame = CGRectMake(_SignLabel.frame.origin.x , _SignLabel.frame.origin.y + _SignLabel.frame.size.height + 5, (self.frame.size.width - _SignLabel.frame.origin.x - 90) / 2, 0.075 * self.frame.size.width);
        } else {
            my_vc = (My_ViewController *)viewcontroller;
            _headerButton.frame = CGRectMake(_SignLabel.frame.origin.x , _SignLabel.frame.origin.y + _SignLabel.frame.size.height + 5, self.frame.size.width * 0.36, 0.075 * self.frame.size.width);
            other_vc = nil;
        }
    }
    return self;
}
- (void)requestOwnInfor:(NSString *)uid
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSDictionary *data = [[NSDictionary alloc]init];
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/show",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict= responseObject;
        //         NSLog(@"获取到的数据为：%@",dict);
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSMutableDictionary *datadic = [[NSMutableDictionary alloc] initWithDictionary:[dict objectForKey:@"data"]];
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeTitle" object:datadic];
        if (my_vc == nil) {
            other_vc.titleLabel.text = [datadic valueForKey:@"username"];
            other_vc.titleLabel.font = [UIFont boldSystemFontOfSize:20];
            other_vc.avatarURLStr = [datadic valueForKey:@"avatar"];
        } else {
            my_vc.titleLabel.text = [datadic valueForKey:@"username"];
            my_vc.titleLabel.font = [UIFont boldSystemFontOfSize:20];
            my_vc.account = [datadic valueForKey:@"account"];
            [userDefaults setObject:[datadic valueForKey:@"username"] forKey:@"username"];
            [userDefaults setObject:[datadic valueForKey:@"avatar"] forKey:@"avatar"];
        }
        if ([[datadic valueForKey:@"introduce"] isKindOfClass:[NSNull class]]) {
            [datadic setObject:@"这家伙来自外星，还没学会地球语言" forKey:@"introduce"];
        }
        self.meta = [NSDictionary dictionaryWithDictionary:[dict valueForKey:@"meta"]];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadRelation" object:dict];
        self.userInformation = [[UserInfor alloc] init];
        [_userInformation setValuesForKeysWithDictionary:datadic];
        [userDefaults setObject:datadic forKey:@"myDictionary"];
        [self setUserInformationWithModel:_userInformation uid:uid];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)createSubviews
{
    
    self.avatar = [[UIImageView alloc] initWithFrame:CGRectMake(15, 10, self.frame.size.width * 0.2343, self.frame.size.width * 0.2343)];
    _avatar.image = [UIImage imageNamed:@"default_head"];
    [self addSubview:_avatar];
    
    self.sexImg = [[UIImageView alloc] initWithFrame:CGRectMake(_avatar.frame.origin.x + _avatar.frame.size.width + 12.5, 14, self.frame.size.width * 0.0344, 0.0406 *self.frame.size.width)];
    _sexImg.image = [UIImage imageNamed:@"alines"];
    [self addSubview:_sexImg];
    
    self.locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(_sexImg.frame.origin.x + _sexImg.frame.size.width + 5, _sexImg.frame.origin.y, 100, 0.0406 *self.frame.size.width)];
    _locationLabel.textColor = [UIColor blackColor];
    _locationLabel.textAlignment = NSTextAlignmentLeft;
    _locationLabel.font = [UIFont systemFontOfSize:13.0];
    _locationLabel.adjustsFontSizeToFitWidth = YES;
    [self addSubview:_locationLabel];
    
    self.SignLabel = [[UILabel alloc] initWithFrame:CGRectMake(_sexImg.frame.origin.x,_sexImg.frame.origin.y + _sexImg.frame.size.height + 3, self.frame.size.width * 0.65, 0.0781 *self.frame.size.width)];
    _SignLabel.textColor = [UIColor colorWithRed: 153 / 255.0 green:153 / 255.0  blue:153 / 255.0 alpha:1.0f];
    _SignLabel.numberOfLines = 0;
    _SignLabel.font = [UIFont systemFontOfSize:13.0f];
    _SignLabel.textAlignment = NSTextAlignmentLeft;
//    _SignLabel.minimumScaleFactor = 1;
    [_SignLabel setAdjustsFontSizeToFitWidth:YES];
    _SignLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
    [self addSubview:_SignLabel];
    
    self.headerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _headerButton.frame = CGRectMake(_SignLabel.frame.origin.x , _SignLabel.frame.origin.y + _SignLabel.frame.size.height + 5, self.frame.size.width * 0.36, 0.075 * self.frame.size.width);
    _headerButton.layer.masksToBounds = YES;
    _headerButton.layer.borderColor = [[UIColor blackColor] CGColor];
    _headerButton.layer.borderWidth = 2;
    [self addSubview:_headerButton];

    self.worksBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _worksBtn.frame = CGRectMake(0, _avatar.frame.origin.y + _avatar.frame.size.height + 0.0625 * self.frame.size.width, self.frame.size.width / 3, 0.0937 * self.frame.size.width);
    [_worksBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _worksBtn.titleLabel.font = [UIFont systemFontOfSize:14];
//    _worksBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    [self addSubview:_worksBtn];
    
    self.followedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _followedBtn.frame = CGRectMake(_worksBtn.frame.size.width, _worksBtn.frame.origin.y, self.frame.size.width / 3, 0.0937 * self.frame.size.width);
    [_followedBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _followedBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _followedBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    [self addSubview:_followedBtn];
    
    self.fansBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _fansBtn.frame = CGRectMake(_followedBtn.frame.origin.x + _followedBtn.frame.size.width, _followedBtn.frame.origin.y, self.frame.size.width / 3, 0.0937 * self.frame.size.width);
    [_fansBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _fansBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    _fansBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    [self addSubview:_fansBtn];
    
    UIView *topLine = [[UIView alloc] initWithFrame:CGRectMake(0, _worksBtn.frame.origin.y, self.frame.size.width, 1)];
    topLine.backgroundColor = [UIColor colorWithWhite:0.868 alpha:1.0]  ;
    [self addSubview:topLine];
    UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, _worksBtn.frame.origin.y + _worksBtn.frame.size.height, self.frame.size.width, 1)];
    bottomLine.backgroundColor = [UIColor colorWithWhite:0.868 alpha:1.0];
    [self addSubview:bottomLine];
    UIView *leftLine = [[UIView alloc] initWithFrame:CGRectMake(_followedBtn.frame.origin.x, _followedBtn.frame.origin.y, 1, _followedBtn.frame.size.height)];
    leftLine.backgroundColor = [UIColor colorWithWhite:0.868 alpha:1.0];
    [self addSubview:leftLine];
    UIView *rightLine = [[UIView alloc] initWithFrame:CGRectMake(_fansBtn.frame.origin.x, _fansBtn.frame.origin.y, 1, _fansBtn.frame.size.height)];
    rightLine.backgroundColor = [UIColor colorWithWhite:0.868 alpha:1.0];
    [self addSubview:rightLine];
}
- (void)setUserInformationWithModel:(UserInfor *)model uid:(NSString *)uid
{
    //头像
    [_avatar setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:[UIImage imageNamed:@"default_head"]];
    //性别
    if ([model.sex isEqualToString:@"1"]) {
        _sexImg.image = [UIImage imageNamed:@"male@3x"];
    } else if ([model.sex isEqualToString:@"2"]) {
        _sexImg.image = [UIImage imageNamed:@"female"];
    } else {
        _sexImg.image = [UIImage imageNamed:@"alines"];
    }
    //位置
    _locationLabel.text = model.location;
    //签名
    _SignLabel.text = model.introduce;
    //修改资料 || 关注状态
    NSNumber *following = [_meta valueForKey:@"following"];
    NSNumber *followed = [_meta valueForKey:@"followed"];
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] isEqualToString:uid]) {
        [_headerButton setTitle:[NSString stringWithFormat:@"积分：%@",model.score] forState:UIControlStateNormal];
    } else {
        if (following.boolValue == NO) {
            [_headerButton setTitle:@"加关注" forState: UIControlStateNormal];
            [_headerButton addTarget:self action:@selector(follow:) forControlEvents:UIControlEventTouchUpInside];
        } else if (following.boolValue == YES && followed.boolValue == NO) {
            [_headerButton setTitle:@"已关注" forState: UIControlStateNormal];
            [_headerButton addTarget:self action:@selector(cancelFollow:) forControlEvents:UIControlEventTouchUpInside];
        } else if (following.boolValue == YES && followed.boolValue == YES){
            [_headerButton setTitle:@"相互关注" forState: UIControlStateNormal];
            [_headerButton addTarget:self action:@selector(cancelFollow:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    _headerButton.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [_headerButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //作品
    NSString *workTitle = [NSString stringWithFormat:@"作品:%@", model.works_count];
    [_worksBtn setTitle:workTitle forState:UIControlStateNormal];
    //关注
    NSString *followTitle = [NSString stringWithFormat:@"关注:%@", model.follow_count];
    [_followedBtn setTitle:followTitle forState:UIControlStateNormal];
    //粉丝
    NSString *fansTitle = [NSString stringWithFormat:@"粉丝:%@", model.fans_count];
    [_fansBtn setTitle:fansTitle forState:UIControlStateNormal];
}
- (void)follow:(UIButton *)sender
{
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] == nil) {
        //提示请先登陆
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{

        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [[AppDelegate shareDelegate] chooseRootViewController];
        }];

//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"未登录" message:@"登录后才能继续操作" delegate:self cancelButtonTitle:@"再看看" otherButtonTitles:nil];
//        //        alert.tag = 12345;
//        [alert addButtonWithTitle:@"去登录"];
//        [alert show];
    }else{
        AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
        //    @"http://123.57.1.143/api/tag/ndiscover";//
        NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/follow", ownuid];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
        [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [netWorkManager stopMonitoring];
            [self requestOwnInfor:ownuid];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
- (void)cancelFollow:(UIButton *)sender
{
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] == nil) {
        //我的
        //提示请先登陆
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{

        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [[AppDelegate shareDelegate] chooseRootViewController];
        }];

//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"未登录" message:@"登录后才能继续操作" delegate:self cancelButtonTitle:@"再看看" otherButtonTitles:nil];
////        alert.tag = 12345;
//        [alert addButtonWithTitle:@"去登录"];
//        [alert show];
    }else{
        AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
        NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/unfollow", ownuid];
         AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
        NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
        [manager POST:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [netWorkManager stopMonitoring];
            [self requestOwnInfor:ownuid];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
      }
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
//    if (alertView.tag==12345){
        if (buttonIndex == 0) {
            
        } else if (buttonIndex == 1){
            //跳到登陆页
            [[AppDelegate shareDelegate] chooseRootViewController];
        }
//    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
